#!/usr/bin/python
# coding=utf-8

import sys
import json
import os
from optparse import OptionParser


def format_data():
    conf_dict = {}
    this_file_path = os.path.dirname(os.path.join(os.getcwd(), sys.argv[0]))
    with open(os.path.join(this_file_path, 'varinfo.yml'), 'r') as f:
        lines = f.readlines()
        for line in lines:
            if line.isspace() or line[0] == '#' or line[0] == '-':
                continue
            else:
                line_list = line.split(': ')
                conf_dict.update({line_list[0].strip(): line_list[1].strip()})
    inventroy_json = dict()
    hostip = conf_dict['update_ip']
    runuser = conf_dict['runuser']
    runpwd = conf_dict['runpwd']
    mygroup = conf_dict['mygroup']

    inventroy_json[mygroup] = dict()
    inventroy_json[mygroup]['hosts'] = []
    inventroy_json[mygroup]['hosts'].append(hostip)
    inventroy_json[mygroup]['vars'] = {"ansible_ssh_user": runuser, "ansible_ssh_pass": runpwd}

    print(json.dumps(inventroy_json, indent=4))


if __name__ == '__main__':
    parser = OptionParser()
    parser.add_option("-l", "--list", action="store_true", dest="list", default=False)
    (option, args) = parser.parse_args()
    if option.list:
        format_data()
    else:
        print("Usage %s --list or --host <hostname>".format(sys.argv[0]))

